package com.longge;

import java.util.HashSet;

public class MaximumLength {

    public int maximumLength(String s) {
        HashSet<String> set = new HashSet<>();
        int maxLength = -1;
        for (int i = 0; i < s.length(); i++) {
            for (int j = i; j < s.length(); j++) {
                String substring = s.substring(i, j + 1);
                if (set.add(substring)) {
                    if (checkSpecial(i, j, s)) {
                        if (j - i >= 3||checkThree(i, j, s)){
                            maxLength = Math.max(maxLength, j - i + 1);
                        }
                    }
                }
            }
        }
        return maxLength;
    }

    private boolean checkSpecial(int i, int j, String s) {
        char first = s.charAt(i);
        for (int k = i + 1; k < j + 1; k++) {
            if (s.charAt(k) != first) {
                return false;
            }
        }
        return true;
    }

    private boolean checkThree(int i, int j, String s) {
        String substring = s.substring(i, j + 1);
        int limit = j - i + 1;
        int num = 0;
        for (int k = 0; k <= s.length() - limit; k++) {
            String str = s.substring(k, k + limit);
            if (str.equals(substring)) {
                num++;
            }
            if (num == 3) return true;
        }
        return false;
    }

    public static void main(String[] args) {
        new MaximumLength().maximumLength("aaaa");
    }
}
